package com.icangya.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.icangya.Utils.*;
import com.icangya.Value.FootBall;
import com.icangya.Value.StaticValue;
import com.icangya.domain.*;
import com.icangya.service.IGoodsService;
import com.icangya.service.IMoneyService;
import com.icangya.service.IUserService;
import com.icangya.wxpay.utils.MD5Utils;
import com.icangya.zhutong.util.HttpRequest;
import com.icangya.zhutong.util.MD5Gen;
import com.icangya.zhutong.util.TimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLEncoder;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.sql.Timestamp;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@CrossOrigin
@RestController
@RequestMapping(value = "/user/menu")
public class MenuController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IMoneyService iMoneyService;

    @Autowired
    private IGoodsService iGoodsService;

    /**
     * 测试用户是否非法登录游戏
     * @param uid
     * @param session
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "loginGame")
    public void loginGame(@RequestParam Long uid,@RequestParam String cy_key,HttpSession session, HttpServletRequest request,
                          HttpServletResponse response) throws Exception {

        String str = "uid=" + uid + "&cy_key=" + StaticValue.SIGN_KEY;//正确的明文
        str = DigestUtils.md5DigestAsHex(str.getBytes("UTF-8"));//第一次md5加密
        String md5Str = DigestUtils.md5DigestAsHex(str.getBytes("UTF-8"));//第二次md5加密
        cy_key = DESUtil.getIstance().decrypt(cy_key, StaticValue.SIGN_KEY).trim();//DES解密 用key
        logger.info(md5Str + "===" + cy_key);
        if (md5Str.equals(cy_key)) {//通过
            User user = iUserService.getUserByUid(uid);
            //request.getSession().setAttribute("Football",user.getOpenId());
            session.removeAttribute(FootBall.FOOT_USER_SESSION);
            session.setAttribute(FootBall.FOOT_USER_SESSION, user);//将登录的用户信息注册进session中

            StringBuffer url = request.getRequestURL();
            String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append
                    (request.getServletContext().getContextPath()).append("/").toString();
//            response.sendRedirect(tempContextUrl + "footballgame/index.html");//Football.html //跳转到我们的游戏界面  足球小将
//            response.sendRedirect("http://"+iDomainService.getDoamin().get(0).getDomainUrl() + "/slyderAdventures/index.html");//Football.html //跳转到我们的游戏界面  足球小将
            response.sendRedirect(StaticValue.WX.BASE_URL + "/m/index.html");

        }else{
            logger.info("校验错误!");
            response.sendRedirect(StaticValue.WX.NO_URL);//非法登录
        }
    }

    /**
     * 获取短信
     * @param mobilePhone
     * @throws InterruptedException
     */
    @RequestMapping(value = "/getShortLetter",method = RequestMethod.POST)
    public JSONObject getShortLetter(String mobilePhone,HttpServletRequest request,HttpServletResponse response) throws InterruptedException {

        if("".equals(mobilePhone) || mobilePhone==null){
            return JSONUtils.getRoot(1,"参数有误。。。","");
        }
        if (!PhoneFormatCheckUtils.isPhoneLegal(mobilePhone)){
            return JSONUtils.getRoot(-1,"手机号码格式错误","");
        }

        int cc = CountUtils.getCountInMinToMax(111111,999999);
        /**
         *    账号：sxdh888hy 密码：Ckhj7g
         *	  账号：sxdh888yx 密码：zKEdCj
         *    hy是发送验证码和通知信息的账号
         *	  17093106236
         */
        String url="http://www.api.zthysms.com/sendSms.do";
        String username="sxdh888hy";    //账号
        String password="Ckhj7g";       // 密码
        String tkey= TimeUtil.getNowTime("yyyyMMddHHmmss");
        String mobile=mobilePhone;  //发送的手机号
        String content= "验证码：" + cc + "【盛世惠农】";   //内容

        JSONObject shortJson = new JSONObject();
        long curtime = System.currentTimeMillis();
        shortJson.put("cc",cc);
        shortJson.put("time",curtime);
        request.getSession().setAttribute(mobilePhone,shortJson);

        logger.info("当前"+mobilePhone+"的session：" + request.getSession().getAttribute(mobilePhone));
        //String time="2016-09-06 17:48:22";//定时信息所需参数时间格式为yyyy-MM-dd HH:mm:ss
        String xh="";
        try {
            content= URLEncoder.encode(content, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String param="url="+url+"&username="+username+"&password="+ MD5Gen.getMD5(MD5Gen.getMD5(password)+tkey)+"&tkey="+tkey+"&mobile="+mobile+"&content="+content+"&xh="+xh;
        //String param="url="+url+"&username="+username+"&password="+MD5Gen.getMD5(MD5Gen.getMD5(password)+tkey)+"&tkey="+tkey+"&time="+time+"&mobile="+mobile+"&content="+content+"&xh="+xh;//定时信息url输出
        String ret= HttpRequest.sendPost(url,param);//定时信息只可为post方式提交
        System.out.println("ret:"+ret);
        System.out.println(param);

        return  JSONUtils.getRoot(0,"发送成功！若未收到短信，请稍后重试！",null);

    }

    /**
     * 新用户注册
     * @return
     */
    @RequestMapping(value = "setUserRegister",method = RequestMethod.POST)
    public JSONObject setUserRegister(String mobilePhone,String shortletter,String referralCode,String passWord,HttpSession session,HttpServletRequest request){

        if (!PhoneFormatCheckUtils.isPhoneLegal(mobilePhone)) {
            return JSONUtils.getRoot(1, "号码格式错误", "");
        }

        //正则匹配密码为6位的数字和字母（管理员）
        Pattern p1 = Pattern.compile("^[0-9]{6}$");
        Matcher m1 = p1.matcher(passWord);

        if ("".equals(shortletter) || shortletter == null) {
            return JSONUtils.getRoot(1, "短信验证码格式错误", "");
        }
        if ("".equals(mobilePhone) || mobilePhone == null) {
            return JSONUtils.getRoot(1, "手机号码格式错误", "");
        }
        if ("".equals(referralCode) || referralCode == null) {
            return JSONUtils.getRoot(1, "推荐码格式错误", "");
        }
        if ("".equals(passWord) || !(m1.matches()) ) {
            return JSONUtils.getRoot(1, "密码格式错误", "");
        }


        //测试
        //验证推荐码
//        User user=iUserService.getUserByReferralCode(referralCode);
//        if(user==null){
//            return JSONUtils.getRoot(-1, "推荐码错误,该推荐人不存在", null);
//        }
//
//        //修改用户，用户进行注册
//        User u=getTestUser(session);
//        u.setMobilePhone(mobilePhone);
//        u.setParentId(user.getId());
//        //密码加密(规则：密码+proxy_key，使用md5加一次密)
////            passWord = MD5Util.toMD5(passWord + StaticValue.PROXY_KEY).toUpperCase();
//        try {
//            passWord = MD5Utils.getMD5Upper(passWord + StaticValue.REGISTER_KEY);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//        }
//        u.setPassWord(passWord);
//        Boolean bool=iUserService.updateUser(u);
//
//        if(bool){
//            return JSONUtils.getRoot(0, "注册成功。", null);
//        }

        //判断短信是否已超时失效===start
        JSONObject shortJson = (JSONObject) request.getSession().getAttribute(mobilePhone);
        logger.info("登录的手机号码：" + mobilePhone + "");
        logger.info(shortJson.toString());
        long curTime = System.currentTimeMillis();
        long sendTime = shortJson.getLong("time");
        int cc = shortJson.getInteger("cc");
        long needTime = (curTime - sendTime) / 1000;
        logger.info("时间相差：" + needTime + "秒！");

        if (needTime > 63) {//短信失效时间为120，加上程序消耗时间可能产生的误差，所以设置为 123 秒
            request.getSession().removeAttribute(mobilePhone);
            return JSONUtils.getRoot(-6, "短信超时", "");
            //判断短信是否已超时失效===end
        } else {
            //判断验证码是否正确
            if (shortletter.equals(String.valueOf(cc))) {
                //验证推荐码
                User user=iUserService.getUserByReferralCode(referralCode);
                if(user==null){
                    return JSONUtils.getRoot(-1, "推荐码错误,该推荐人不存在", null);
                }

                //修改用户，用户进行注册
                User u=getTestUser(session);
                u.setMobilePhone(mobilePhone);
                u.setParentId(user.getId());
                //密码加密(规则：密码+proxy_key，使用md5加一次密)
//            passWord = MD5Util.toMD5(passWord + StaticValue.PROXY_KEY).toUpperCase();
                try {
                    passWord = MD5Utils.getMD5Upper(passWord + StaticValue.REGISTER_KEY);
                } catch (NoSuchAlgorithmException e) {
                    e.printStackTrace();
                }
                u.setPassWord(passWord);
                Boolean bool=iUserService.updateUser(u);

                if(bool){
                    return JSONUtils.getRoot(0, "注册成功。", null);
                }

            }else{
                return JSONUtils.getRoot(-5, "短信验证码错误", null);
            }
        }

        return JSONUtils.getRoot(2,"请重新扫码登录","");

    }

    /**
     * 获取最新的用户信息
     * @return
     */
    @RequestMapping(value = "getUser",method = RequestMethod.GET)
    public JSONObject selectUser(HttpSession session){
        try {
            User user = getTestUser(session);
            user=iUserService.getUserByUid(user.getId());
            if(user==null){
                return JSONUtils.getRoot(1, "用户信息为空，请稍后重试", null);
            }
            return JSONUtils.getRoot(0,"success",user);
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }

    /**
     * 用户的用户详情
     * @return
     */
    @RequestMapping(value = "getUserOpenId",method = RequestMethod.GET)
    public JSONObject selectUserByOpnId(HttpSession session){
        try {
            User user = getTestUser(session);

            Balance balance = iMoneyService.getUserBalanceByUid(user.getId());//用户余额
            if (balance == null) {
                return JSONUtils.getRoot(1, "用户余额信息为空，请稍后重试", null);
            }

            JSONObject jsonObject = new JSONObject();
//        jsonObject.put("user",user);
            jsonObject.put("headImgUrl", user.getHeadImgUrl());
            jsonObject.put("nickName", user.getNickName());
            jsonObject.put("money", balance.getMoney());//用户余额
            jsonObject.put("userPoint", balance.getUserPoint());//商城积分
            return JSONUtils.getRoot(0,"success",jsonObject);
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }

    /**
     * 用户的历史升级记录
     * @return
     */
    @RequestMapping(value = "getGoodsUpgrade",method = RequestMethod.GET)
    public JSONObject getGoodsUpgradeRecord(HttpSession session){
        try {
            User user = getTestUser(session);
            List list = iUserService.getGoodsUpgradeByUserId(user.getId());
            if (list == null) {
                return JSONUtils.getRoot(1, "用户没有升级记录。。。。。。。。。。", null);
            }
            return JSONUtils.getRoot(0,"success",list);
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }


    /**
     * 获取猜奇偶的榜单信息
     * @return
     */
    @RequestMapping(value = "getOdevityRecord",method = RequestMethod.GET)
    public JSONObject getOdevityRecord(HttpSession session){
        try {
            List list = iUserService.getOdevityAll();
            if (list == null) {
                return JSONUtils.getRoot(1, "没有榜单信息。。。", null);
            }
            return JSONUtils.getRoot(0,"success",list);
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }

    /**
     * 红包记录
     * @return
     */
    @RequestMapping(value = "getRedPacketRecord",method = RequestMethod.GET)
    public JSONObject getRedPacketRecord(HttpSession session){
        try {
            User user = getTestUser(session);
            List list = iUserService.getRedPacketRecord(user.getId());
            if (list == null) {
                return JSONUtils.getRoot(1, "没有红包信息。。。", null);
            }
            return JSONUtils.getRoot(0,"success",list);
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }


    /**
     * 查询用户订单记录
     * @return
     */
    @RequestMapping(value = "getUserOrderRecord",method = RequestMethod.GET)
    public JSONObject getUserOrderRecord(HttpSession session){
        try {
            User user = getTestUser(session);
            List list = iUserService.getOrdersByUserId(user.getId());
            if (list == null) {
                return JSONUtils.getRoot(1, "没有订单记录。。。", null);
            }
            return JSONUtils.getRoot(0,"success",list);
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }

    /**
     * 查询用户充值记录
     * @return
     */
    @RequestMapping(value = "getUserRechargeRecord",method = RequestMethod.GET)
    public JSONObject getUserRechargeRecord(HttpSession session){
        try {
            User user = getTestUser(session);
            List list = iMoneyService.getRechargeRecordByOpenId(user.getOpenId());
            if (list == null) {
                return JSONUtils.getRoot(1, "没有充值记录。。。", null);
            }
            return JSONUtils.getRoot(0,"success",list);
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }


    /**
     * 查询用户推广记录（直推人）
     * @return
     */
    @RequestMapping(value = "getUserFirstProxy",method = RequestMethod.GET)
    public JSONObject getUserFirstProxy(HttpSession session){
        try {
            User user = getTestUser(session);

            List<User> userList=iUserService.getUserFirstLevel(user.getId());

            if (userList == null) {
                return JSONUtils.getRoot(1, "没有直推人数。。。", null);
            }
            JSONArray jsonArray=new JSONArray();
            for (User use : userList){
                JSONObject jsonObject=new JSONObject();
                jsonObject.put("headImgUrl",use.getHeadImgUrl());
                jsonObject.put("nickName",use.getNickName());
                jsonObject.put("accountNum",use.getAccountNum());
                jsonObject.put("orderCount",iGoodsService.getUserOrderCountByNow(use.getId()));

                jsonArray.add(jsonObject);

            }

            return JSONUtils.getRoot(0,"success",jsonArray);
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }


    /**
     * 用户实名认证
     * @param session
     * @param shortletter 验证码
     * @param idCardNum 身份证号码
     * @param realName 真实姓名
     * @param sex  性别
     * @return
     */
    @RequestMapping(value = "setUserRealName",method = RequestMethod.POST)
    public JSONObject setUserRealName(HttpSession session,HttpServletRequest request,String shortletter,String idCardNum,String realName,long sex){

        if(shortletter==null || "".equals(shortletter) || idCardNum==null || "".equals(idCardNum) || realName==null || "".equals(realName)){

            return JSONUtils.getRoot(1, "参数有误", "");
        }

        if(!(sex==1 || sex==0)){
            return JSONUtils.getRoot(1, "性别错误", "");
        }

        try {
            User user = getTestUser(session);

            //判断短信是否已超时失效===start
            JSONObject shortJson = (JSONObject) request.getSession().getAttribute(user.getMobilePhone());
            logger.info("登录的手机号码：" + user.getMobilePhone() + "");
            logger.info(shortJson.toString());
            long curTime = System.currentTimeMillis();
            long sendTime = shortJson.getLong("time");
            int cc = shortJson.getInteger("cc");
            long needTime = (curTime - sendTime) / 1000;
            logger.info("时间相差：" + needTime + "秒！");

            if (needTime > 63) {//短信失效时间为120，加上程序消耗时间可能产生的误差，所以设置为 123 秒
                request.getSession().removeAttribute(user.getMobilePhone());
                return JSONUtils.getRoot(-6, "短信超时", "");
                //判断短信是否已超时失效===end
            } else {
                //判断验证码是否正确
                if (shortletter.equals(String.valueOf(cc))) {
                    //修改用户，用户进行实名认证
                    user.setRealName(realName);
                    user.setSex(sex);
                    user.setIdCardNum(idCardNum);

                    Boolean bool=iUserService.updateUser(user);
                    if(bool){
                        return JSONUtils.getRoot(0, "提交成功。", null);
                    }

                }else{
                    return JSONUtils.getRoot(-5, "短信验证码错误", null);
                }
            }

            return JSONUtils.getRoot(1,"提交失败","");
        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }


    /**
     * 添加用户申请提现
     * @return
     */
    @RequestMapping(value = "setUserWithdraw",method = RequestMethod.POST)
    public synchronized JSONObject setUserWithdraw(HttpSession session, double money, String cardName, String bankName, String cardNum){
        try {
            if (money < 0 || cardName == null || "".equals(cardName) || bankName == null || "".equals(bankName) || cardNum == null || "".equals(cardNum)) {
                return JSONUtils.getRoot(1, "参数有误", "");
            }

            User user = getTestUser(session);
            Balance balance = iMoneyService.getUserBalanceByUid(user.getId());

            if (balance == null) {
                return JSONUtils.getRoot(1, "用户异常登录。。。", null);
            }

            if(money > (balance.getMoney()/100)){
                return JSONUtils.getRoot(1, "用户余额不足。。。", null);
            }

            UserWithdrawRecord withdrawRecord=new UserWithdrawRecord();
                withdrawRecord.setOpenId(user.getOpenId());
                withdrawRecord.setUid(user.getId());
                withdrawRecord.setNickName(user.getNickName());
                withdrawRecord.setHeadImgUrl(user.getHeadImgUrl());
                withdrawRecord.setMoney(money);
                withdrawRecord.setCardName(cardName);
                withdrawRecord.setCardNum(cardNum);
                withdrawRecord.setBankName(bankName);
                withdrawRecord.setStatus(1);//提现状态  0：成功  1：待审核  2：拒绝提现
                withdrawRecord.setCreateTime(new Timestamp(new Date().getTime()));

                //添加用户提现记录
           UserWithdrawRecord userWithdrawRecord= iUserService.saveUserWithdrawRecord(withdrawRecord);
           if(userWithdrawRecord!=null){

               //修改用户余额信息
               balance.setMoney((long) (balance.getMoney() -money*100));

               Boolean  bool=  iMoneyService.updateBalanceByOpenId(balance);

               if(bool){
                    return JSONUtils.getRoot(0,"提交成功，待审核","");
               }
           }
            return JSONUtils.getRoot(1, "提交失败，请稍后重试", null);

        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }

    /**
     * 查询兑换商品列表
     * @return
     */
    @RequestMapping(value = "getGoodsConvert",method = RequestMethod.GET)
    public JSONObject getGoodsConvert(){
        try {

            //查询上架的兑换商品
            List<GoodsConvert> goodsList=iGoodsService.getGoodsConvertByStatus(1L);

            if(goodsList==null){
                return JSONUtils.getRoot(1, "没有商品可兑换。。。", null);
            }
            return JSONUtils.getRoot(0,"success",goodsList);

        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }

    /**
     * 查询单个兑换商品的id
     * @param id
     * @return
     */
    @RequestMapping(value = "getGoodsConvertDetails",method = RequestMethod.POST)
    public JSONObject getGoodsConvertDetails(HttpSession session,  long id){
        try {
            if(id <0 ){
                return JSONUtils.getRoot(1, "参数有误。。。", null);
            }

            User user=getTestUser(session);
            Balance balance=iMoneyService.getUserBalanceByUid(user.getId());
            if(balance == null){
                return JSONUtils.getRoot(1, "用户信息为空，请稍后重试。。。", null);
            }
            GoodsConvert goodsConvert=iGoodsService.getGoodsConvertById(id);

            if(goodsConvert==null){
                return JSONUtils.getRoot(1, "没有商品可兑换。。。", null);
            }
            //该兑换商品已下架
            if(goodsConvert.getStatus()==0){
                return JSONUtils.getRoot(1, "该商品已下架。。。", null);
            }

            List goodsDetails=iGoodsService.getGoodsConvertDetailsByGid(goodsConvert.getId());
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("goods",goodsConvert);
            jsonObject.put("imgUrl",goodsDetails);
            jsonObject.put("money",balance.getMoney());
            jsonObject.put("userPoint",balance.getUserPoint());


            if(goodsDetails==null){
                jsonObject.put("imgUrl","");
            }

            return JSONUtils.getRoot(0,"success",jsonObject);

        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }

    /**
     * 查询兑换商品列表
     * @return
     */
    @RequestMapping(value = "testDate",method = RequestMethod.GET)
    public JSONObject testDate(){
            return JSONUtils.getRoot(2, "请重新登录!", FormatUtil.getOrderId(new Date()));
    }



    /**
     * 添加兑换商品订单
     * @param id   商品id
     * @param goodCount  订单数量
     * @param name  收货人姓名
     * @param mobilePhone  手机号码
     * @param address  地址
     * @return
     */
    @RequestMapping(value = "saveGoodsConvertOrder",method = RequestMethod.POST)
    public synchronized JSONObject saveGoodsConvertOrder(HttpSession session,long id,long goodCount,String name,String mobilePhone,String address){
        try {

            if(id < 0 || goodCount < 0 || "".equals(name) || name == null || "".equals(mobilePhone) || mobilePhone ==null || "".equals(address) || address ==null){

                return JSONUtils.getRoot(1, "参数有误。。。", null);
            }
            User user=getTestUser(session);

            if(user == null){
                return JSONUtils.getRoot(1, "用户信息为空，请稍后重试。。。", null);
            }

            GoodsConvert goodsConvert=iGoodsService.getGoodsConvertById(id);//获取商品信息

            if(goodsConvert==null){
                return JSONUtils.getRoot(1, "没有商品可兑换。。。", null);
            }
            //该兑换商品已下架
            if(goodsConvert.getStatus()==0){
                return JSONUtils.getRoot(1, "该商品已下架。。。", null);
            }

            //获取用户余额信息
            Balance balance=iMoneyService.getUserBalanceByUid(user.getId());
            if(balance == null){
                return JSONUtils.getRoot(1, "用户信息为空，请稍后重试。。。", null);
            }

            if(balance.getUserPoint() < goodsConvert.getPoint() * goodCount){
                return JSONUtils.getRoot(-1, "用户积分不够兑换该商品。。。", null);
            }

            int postage= (int) (goodsConvert.getFirstPostage()+(goodCount-1)*goodsConvert.getOtherPostage());//邮费

            if(balance.getMoney() < postage * 100 ){
                return JSONUtils.getRoot(-2, "用户余额不足支付邮费，请充值后兑换商品。。。", null);
            }

            balance.setMoney(balance.getMoney() -( postage*100));
          boolean bool=  iMoneyService.updateBalanceByOpenId(balance);//修改用户的余额
//            String orderId= String.valueOf(date.getYear()+date.getMonth()+date.getDay()+date.getHours()+date.getMinutes()+date.getSeconds());
//           orderId=orderId+FormatUtil.getMillis(date);
//            Random random=new Random();
//            int r=random.nextInt(10);
//            orderId=orderId+r;
            if(bool) {
                RwGoodOrder goodOrder = new RwGoodOrder();//生成订单
                Date date = new Date();
                goodOrder.setOrderId(FormatUtil.getOrderId(date));//订单号
                goodOrder.setPrice(goodsConvert.getPoint());//订单单价  积分
                goodOrder.setSumPices(0);//订单总额，，积分兑换获取商品
                goodOrder.setRemark("");//备注
                goodOrder.setNumPiece(goodCount);//订单数量
                goodOrder.setCreateTime(new Timestamp(date.getTime()));//创建时间
                goodOrder.setUserid(user.getId());//订单用户id
                goodOrder.setOpenid(user.getOpenId());//订单用户openid
                goodOrder.setOrderUserImg(user.getHeadImgUrl());//订单用户头像；
                goodOrder.setOrderUserNickName(user.getNickName());//订单用户昵称；
                goodOrder.setPaystatus(1);//订单是否已付款  1：已付款，0：未付款
                goodOrder.setPickUpstatus(1);//订单是否提货  1：提货，0：未提货
                goodOrder.setSendStatus(0);//订单是否已发货  1：已发货，0：未发货
                goodOrder.setMainPic(goodsConvert.getMainPic());//订单主图
                goodOrder.setOrderAddress(address);//订单地址；
//            goodOrder.setAddressId();//地址id
                goodOrder.setMobilePhone(mobilePhone);//用户手机号码
                goodOrder.setIntro(goodsConvert.getIntro());//用户手机号码
                goodOrder.setExpressComp("");//快递号
                goodOrder.setExpressNum("");//快递公司
                goodOrder.setPostage(postage);//邮费
                goodOrder.setConvertStatus(0);//商品是否属于兑换商品   0:兑换专区   1：非兑换专区
                goodOrder.setName(name);//收件人名称

               RwGoodOrder order= iGoodsService.saveRwGoodOrder(goodOrder);

               if(order != null){
                   return JSONUtils.getRoot(0,"success","");
               }


            }

            return JSONUtils.getRoot(1, "修改用户余额信息失败，请稍后重试。。。", null);

        }catch (NullPointerException e){
            return JSONUtils.getRoot(2, "请重新登录!", null);
        }

    }

    /**
     * 修改密码
     * @return
     */
    @RequestMapping(value = "updateUserByPwd",method = RequestMethod.POST)
    public JSONObject updateUserByPwd(@RequestParam String mobilePhone,@RequestParam String passWord,@RequestParam String passWord2,HttpSession session){
        if(passWord2==null || passWord ==null || "".equals(passWord) || "".equals(passWord2)) {
            return JSONUtils.getRoot(1, "参数不能为空", "");
        }

        if(!passWord.equals(passWord2)){
            return JSONUtils.getRoot(1, "俩次密码不一致", "");
        }

        //正则匹配密码为6位的数字
        Pattern p1 = Pattern.compile("^[0-9]{6,12}$");
        Matcher m = p1.matcher(passWord);

        if (m.matches()) {
            //密码加密(规则：密码+proxy_key，使用md5加一次密)
            try {
                passWord = MD5Utils.getMD5Upper(passWord + StaticValue.REGISTER_KEY);
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }else{
//            1，密码全部是数字
            return JSONUtils.getRoot(1,"旧密码长度不符合 ，密码的长度为6-12位的数字加字母","");
        }


        User user=getTestUser(session);

        if(!mobilePhone.equals(user.getMobilePhone())){
            return JSONUtils.getRoot(1,"手机号码不存在","");
        }

        user.setPassWord(passWord);//修改用户密码
        Boolean bool=iUserService.updateUser(user);

        if(bool){
            return JSONUtils.getRoot(0,"修改密码成功","");
        }

        return JSONUtils.getRoot(2,"系统缓慢，请稍后重试！！","");
    }


    /**
     * 生成二维码
     * @param session
     * @return
     */
    @RequestMapping(value = "getQRCode",method = RequestMethod.GET)
    public JSONObject getSubLevelCommission(HttpServletRequest request,HttpSession session) {
        User userDO = getTestUser(session);
//        userDO=iUserService.getUserByUid(userDO.getId());
//        String openId=userDO.getOpenId();//前端测试
        //userDO=iUserService.getUserByUid(2);
        logger.info("====二维码==="+userDO.getQrCode().length());

        String imgpath = GenerateImage(userDO.getQrCode(),request, String.valueOf(userDO.getId()));
        if (imgpath==null){
            return JSONUtils.getRoot(-1, "faild", "图片为空！");
        }

        return JSONUtils.getRoot(0, "success", imgpath);
    }


    // 判断文件是否存在
     public boolean judeFileExists(File file) {

         if (file.exists()) {
//             System.out.println("file exists");
             return true;
         } else {
//             System.out.println("file not exists, create it ...");
//             try {
//                 file.createNewFile();
//             } catch (IOException e) {
//                 // TODO Auto-generated catch block
//                 e.printStackTrace();
//             }
             return false;
         }
     }
    //base64字符串转化成图片
    private String GenerateImage(String imgStr,HttpServletRequest request,String userid)
    {   //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            File file=new File("upload/user/img_qrcode/");
            if(!file.exists()){
                file.mkdirs();
            }
            //生成jpeg图片 ,上传的目录地址
            String imgFilePath= request.getSession().getServletContext().getRealPath("/")+"upload/user/img_qrcode/"+userid+".jpg";//新生成的图片
            //生成jpeg图片 ,上传的目录地址
//            String imgFilePath = "D:\\360CloudUI\\tupian\\new.jpg";//新生成的图片

            //为什么要注释掉？不判断是否有图片，无论有没有，都生成新的图片。
//            if (judeFileExists(new File(imgFilePath))){
//                return "/img_qrcode/"+userid+".jpg";
//            }

            System.out.println(b.length+"==imgFilePath==="+imgFilePath);
            System.out.println(b.length+"==imgFilePath==="+imgFilePath);
            System.out.println(b.length+"==imgFilePath==="+imgFilePath);
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return "upload/user/img_qrcode/"+userid+".jpg";
        }
        catch (Exception e)
        {
            return e.getMessage();
        }
    }




    public User getTestUser(HttpSession session){
//        User user = (User) session.getAttribute(FootBall.FOOT_USER_SESSION);
        User user=iUserService.getUserByUid(1L);
        return user;
    }


}
